package cn.stylefeng.guns.modular.robot.cmd.impl;

import cn.stylefeng.guns.modular.robot.cmd.abs.AbstractCmd;
import cn.stylefeng.guns.modular.robot.entity.DfInfo;
import cn.stylefeng.guns.modular.robot.entity.Group;
import cn.stylefeng.guns.modular.robot.entity.enums.GroupType;
import cn.stylefeng.guns.modular.robot.service.DfInfoService;
import cn.stylefeng.guns.modular.robot.service.GroupService;
import cn.stylefeng.guns.modular.robot.utils.RobotUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.objects.Chat;
import org.telegram.telegrambots.meta.api.objects.Update;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Objects;

@Slf4j
@Service
@Transactional
public class CmdDf extends AbstractCmd {

    @Resource
    private DfInfoService dfInfoService;
    @Resource
    private GroupService groupService;

    @Override
    public void exec(Update update, TelegramLongPollingBot bot) {
        Chat chat = update.getMessage().getChat();
        Long chatId = update.getMessage().getChatId();
        String text = update.getMessage().getText();
        Integer messageId = update.getMessage().getMessageId();
        String title = chat.getTitle();
        if (StringUtils.isBlank(text)) {
            return;
        }
        Group group = groupService.getGroupByTgGroupId(chatId);
        if(Objects.isNull(group) || !GroupType.DF.equals(group.getType())){
            RobotUtils.sendText(chatId, "此群不支持该指令！", bot);
        }
        String[] split = text.split("\n");
        if (split.length < 3) {
            return;
        }
        String accountRow = split[1];
        String amountRow = split[2];
        amountRow = amountRow.replace("：", ":");
        accountRow = accountRow.replace("：", ":");
        if (!amountRow.contains(":") || !accountRow.contains(":")) {
            return;
        }
        String amount= amountRow.split(":")[1];
        String account=accountRow.split(":")[1];
        DfInfo dfInfo=new DfInfo();
        dfInfo.setGroupId(chatId);
        dfInfo.setGroupName(title);
        dfInfo.setGroupUserName(group.getCreateBy());
        dfInfo.setMessageId(messageId);
        dfInfo.setIsHandle(false);
        dfInfo.setAccount(account);
        dfInfo.setAmount(new BigDecimal(amount));
        dfInfo.setCreateTime(new Date());
        dfInfo.setCreateBy(update.getMessage().getFrom().getUserName());
        dfInfoService.save(dfInfo);
    }

    @Override
    public String getCmdName() {
        return "/DF";
    }

    @Override
    public String getDescribe() {
        return "/DF                           代付指令\n";
    }
}
